package com.kanq.common.utils;

import com.hankcs.hanlp.HanLP;

import java.util.*;
import java.util.stream.Collectors;

public class TitleGeneratorUtils {

    // 停用词列表升级版（包含更多常见虚词）
    private static final Set<String> STOP_WORDS = new HashSet<>(Arrays.asList(
            "的", "是", "在", "了", "和", "有", "就", "也", "都", "这"
    ));

    public static String generateTitle(String content) {
        if (content == null || content.trim().isEmpty()) {
            return "新对话";
        }

        try {
            List<String> keywords = extractKeywordsWithHanLP(content);
            return formatTitle(keywords);
        } catch (Exception e) {
            // HanLP异常时回退基础算法
            return formatTitle(extractKeywordsBasic(content));
        }
    }

    /**
     * 使用HanLP提取关键词（更精准的语义分析）
     */
    private static List<String> extractKeywordsWithHanLP(String content) {
        return HanLP.extractKeyword(content, 3).stream()
                .filter(word -> !STOP_WORDS.contains(word))
                .collect(Collectors.toList());
    }

    /**
     * 备用基础算法（与之前版本兼容）
     */
    private static List<String> extractKeywordsBasic(String content) {
        return Arrays.stream(content.split("[\\s,，.。]+"))
                .filter(word -> !STOP_WORDS.contains(word))
                .sorted((a, b) -> Integer.compare(b.length(), a.length()))
                .limit(3)
                .toList();
    }


    private static String formatTitle(List<String> keywords) {
        if (keywords.isEmpty()) return "新对话";

        // 将关键词用连接符组合
        StringJoiner sj = new StringJoiner("·");
        for (String word : keywords) {
            sj.add(capitalize(word));
        }
        return sj.toString();
    }

    private static String capitalize(String str) {
        if (str == null || str.isEmpty()) return "";
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);
    }
}
